//
//  UICGoogleMapsAPI.m
//  MapDirectionsV3
//
//  Created by Kishikawa Katsumi on 09/12/19.
//  Copyright Kishikawa Katsumi 2009. All rights reserved.
//

#import "UICGoogleMapsAPI.h"
#import "JSON.h"

@implementation UICGoogleMapsAPI

@synthesize delegate;
@synthesize isInitialized;

- (id)init {
    if (self = [super init]) {
        evaluator = [[UIWebView alloc] initWithFrame:CGRectZero];
        evaluator.delegate = self;
        NSString *path = [[NSBundle mainBundle] pathForResource:@"api" ofType:@"html"];
        [evaluator loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];
    }
    return self;
}

- (void)dealloc {
    [evaluator release];
    [super dealloc];
}

- (void)drawRect:(CGRect)rect {
    // Nothing to do.
}

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script {
    NSLog(@"%s", __func__);
    return [evaluator stringByEvaluatingJavaScriptFromString:script];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%s", __func__);
	NSString *requestString = [[request URL] absoluteString];
	NSArray *params = [requestString componentsSeparatedByString:@"::"];
    
    NSString *function = [params objectAtIndex:0];
    
	if ([params count] > 1 && [function isEqualToString:@"directions-v3"]) {
        NSString *param1 = [params objectAtIndex:1];
		if([param1 isEqualToString:@"route"]) {
            NSString *param2 = [params objectAtIndex:2];
            id JSONValue = [[param2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] JSONValue];
            if (!JSONValue) {
                if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didFailWithMessage:)]) {
                    [delegate goolgeMapsAPI:self didFailWithMessage:param2];
                }
            } else {
                if ([self.delegate respondsToSelector:@selector(goolgeMapsAPI:didGetObject:)]) {
                    [delegate goolgeMapsAPI:self didGetObject:JSONValue];
                }
            }
		}
		return NO;
	}
    
	return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if (!isInitialized) {
        isInitialized = YES;
        if ([delegate respondsToSelector:@selector(goolgeMapsAPIDidFinishInitialize:)]) {
            [delegate goolgeMapsAPIDidFinishInitialize:self];
        }
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    if (!isInitialized) {
        if ([delegate respondsToSelector:@selector(goolgeMapsAPI:didFailInitializeWithError:)]) {
            [delegate goolgeMapsAPI:self didFailInitializeWithError:error];
        }
    }
}

@end
